package com.shuidi.retrofittextactivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private TextView content;
    private Button button;
    OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.button);
        content = (TextView)findViewById(R.id.content);

        //"http://www.wuhucourt.gov.cn/tmp/jsonp/ajax.shtml?id=189&nums=10";//新闻
        //https://api.douban.com/v2/book/search?q=金瓶梅&tag=&start=0&count=1

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

                 okHttpClient= new OkHttpClient.Builder()
                        .retryOnConnectionFailure(true)
                        .connectTimeout(11, TimeUnit.SECONDS)
                        .readTimeout(11,TimeUnit.SECONDS)
                        .addInterceptor(interceptor)
                        .build();

                 init();
            }
        });
    }

    private void init(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.wuhucourt.gov.cn/tmp/jsonp/")
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .build();
        NewRetrofitService service = retrofit.create(NewRetrofitService.class);
        Call<Bean> call =  service.getSearchBook(189,1);
        call.enqueue(new Callback<Bean>() {
            @Override
            public void onResponse(Call<Bean> call, Response<Bean> response) {
                content.setText(response.body().getData().get(0).getTitle());
            }
            @Override
            public void onFailure(Call<Bean> call, Throwable t) {
            }
        });
    }
}
